<template>
    <el-container direction="vertical">
        <el-collapse v-model="activeSetting" accordion v-for="(setting,index) in settings" v-bind:key="index">
            <el-collapse-item name="0" v-if="index === 0">
                <template slot="title">
                    <b><i class="el-icon-plus"></i> 新增配置项</b>
                </template>
                <el-form :model="setting" status-icon :rules="rules" label-position="right" ref="settingForm" label-width="110px">
                    <el-form-item label="唯一标识" prop="key">
                        <el-input type="text" v-model="setting.key" placeholder="配置项Key值，添加后不可修改"></el-input>
                    </el-form-item>
                    <el-form-item label="存储类型" prop="type">
                        <el-select v-model="setting.type" placeholder="请选择">
                            <el-option
                                    v-for="item in types"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="设置名称" prop="name">
                        <el-input type="text" v-model="setting.name"></el-input>
                    </el-form-item>
                    <el-form-item label="字符串值" prop="string" v-if="setting.type === 0">
                        <el-input type="text" v-model="setting.string"></el-input>
                    </el-form-item>
                    <el-form-item label="整数值" prop="string" v-if="setting.type === 1">
                        <el-input-number type="number" v-model="setting.int"></el-input-number>
                    </el-form-item>
                    <el-form-item label="布尔值" prop="string" v-if="setting.type === 2">
                        <el-checkbox v-model="setting.bool" :label="setting.bool ? '是/True/Yes' : '否/False/No'" border></el-checkbox>
                    </el-form-item>
                    <el-form-item label="字符串数组" prop="string" v-if="setting.type === 3">
                        <div v-for="(str, index) in setting.array" v-bind:key="index">
                            <el-input size="mini" v-model="setting.array[index]">
                                <el-button slot="append" icon="el-icon-delete" title="删除" @click="delArrayVal(setting, index)"></el-button>
                            </el-input>
                        </div>
                        <el-button size="mini" type="success" style="width: 100%" @click="addArrayVal(setting)">+ 增加</el-button>
                    </el-form-item>
                    <el-form-item label="Json" prop="jsonString" v-if="setting.type === 4">
                        <el-input type="textarea" :autosize="true" v-model="setting.jsonString" @change="setJsonVal(setting)"></el-input>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" size="small" @click="addOne(setting, index)">保存</el-button>
                    </el-form-item>
                </el-form>
            </el-collapse-item>
            <el-collapse-item :title="setting.name" :name="index" v-if="index !== 0">
                <el-form :model="setting" status-icon :rules="rules" label-position="right" ref="settingForm" label-width="110px">
                    <el-form-item label="唯一标识" prop="key">
                        <el-input type="text" v-model="setting.key" :readonly="true" :disabled="true"></el-input>
                    </el-form-item>
                    <el-form-item label="存储类型" prop="type">
                        <el-select v-model="setting.type" placeholder="请选择" :disabled="setting.builtIn">
                            <el-option
                                    v-for="item in types"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="设置名称" prop="name">
                        <el-input type="text" v-model="setting.name" :readonly="setting.builtIn" :disabled="setting.builtIn"></el-input>
                    </el-form-item>
                    <el-form-item label="字符串值" prop="string" v-if="setting.type === 0">
                        <el-input type="text" v-model="setting.string"></el-input>
                    </el-form-item>
                    <el-form-item label="整数值" prop="string" v-if="setting.type === 1">
                        <el-input-number type="number" v-model="setting.int"></el-input-number>
                    </el-form-item>
                    <el-form-item label="布尔值" prop="string" v-if="setting.type === 2">
                        <el-checkbox v-model="setting.bool" :label="setting.bool ? '是/True/Yes' : '否/False/No'" border></el-checkbox>
                    </el-form-item>
                    <el-form-item label="字符串数组" prop="string" v-if="setting.type === 3">
                        <div v-for="(str, index) in setting.array" v-bind:key="index">
                            <el-input size="mini" v-model="setting.array[index]">
                                <el-button slot="append" icon="el-icon-delete" title="删除" @click="delArrayVal(setting, index)"></el-button>
                            </el-input>
                        </div>
                        <el-button size="mini" type="success" style="width: 100%" @click="addArrayVal(setting)">+ 增加</el-button>
                    </el-form-item>
                    <el-form-item label="Json" prop="jsonString" v-if="setting.type === 4">
                        <el-input type="textarea" :autosize="true" v-model="setting.jsonString" @change="setJsonVal(setting)"></el-input>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" size="small" @click="updateOne(setting, index)">保存</el-button>
                        <el-button type="danger" size="small" @click="delOne(index)" v-if="!setting.builtIn">删除</el-button>
                    </el-form-item>
                </el-form>
            </el-collapse-item>
        </el-collapse>
    </el-container>
</template>

<script>
    import AdminService from '../../services/admin.service';
    import Loading from "../../utils/loading";

    export default {
        name: "AdminSetting",
        data() {
            return {
                activeSetting: -1,
                settings: [],
                types: [{
                    value: 0,
                    label: '字符串',
                }, {
                    value: 1,
                    label: '整数',
                }, {
                    value: 2,
                    label: '布尔型',
                }, {
                    value: 3,
                    label: '字符串数组',
                }, {
                    value: 4,
                    label: 'Json',
                }],
                rules: {
                    key: [
                        {required: true, message: '不能为空', trigger: 'blur'},
                        {min: 1, max: 20, message: '长度在1~20个字符', trigger: 'blur'},
                    ],
                    name: [
                        {required: true, message: '不能为空', trigger: 'blur'},
                        {min: 1, max: 80, message: '长度在1~80个字符', trigger: 'blur'},
                    ],
                    jsonString: [
                        {required: true, message: '不能为空，空Json请填{}', trigger: 'blur'},
                        {
                            validator: (rule, value, callback) => {
                                try {
                                    JSON.parse(value);
                                    callback();
                                } catch (e) {
                                    callback(new Error('JSON格式错误' + e.message));
                                }
                            }, trigger: 'blur',
                        },
                    ],
                },
            };
        },
        methods: {
            addArrayVal(setting) {
                setting.array.push('');
            },
            delArrayVal(setting, index) {
                setting.array.splice(index, 1);
            },
            setJsonVal(setting) {
                try {
                    setting.json = JSON.parse(setting.jsonString);
                } catch (e) {
                    this.$message.error(e.message);
                }
            },
            addOne(setting, index) {
                this.$refs['settingForm'][index].validate(async (valid) => {
                    if (valid) {
                        if (setting.type === undefined) {
                            this.$message.warning('请选择存储类型');
                            return;
                        }
                        let info = await AdminService.settingAdd(setting);
                        if (info.code === 1) {
                            this.settings.push(setting);
                            this.settings.splice(0, 1, {
                                string: '',
                                int: 0,
                                bool: false,
                                array: [],
                                json: {},
                                builtIn: false,
                            });
                        } else {
                            this.$message.error(info.msg);
                        }
                    } else {
                        return false;
                    }
                });
            },
            async delOne(index) {
                this.$confirm('即将删除配置 ' + this.settings[index].name + ', 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning',
                }).then(async () => {
                    let info = await AdminService.settingDel(this.settings[index].key);
                    if (info.code === 1) {
                        this.settings.splice(index, 1);
                        this.activeSetting = -1;
                    } else {
                        this.$message.error(info.msg);
                    }
                }).catch(() => {
                });
            },
            async updateOne(setting, index) {
                this.$refs['settingForm'][index].validate(async (valid) => {
                    if (valid) {
                        if (setting.type === undefined) {
                            this.$message.warning('请选择存储类型');
                            return;
                        }
                        let info = await AdminService.settingUpdate(setting);
                        if (info.code === 1) {
                            this.$message.success('更新成功!');
                        } else {
                            this.$message.error(info.msg);
                        }
                    } else {
                        return false;
                    }
                });
            },

        },

        async mounted() {
            Loading.showLoad('正在加载设置列表...');
            let res = await AdminService.settings();
            this.settings = res.data;
            for (let idx in this.settings) {
                this.$set(this.settings[idx], 'jsonString', JSON.stringify(this.settings[idx].json, null, 4));
            }
            this.settings.unshift({
                string: '',
                int: 0,
                bool: false,
                array: [],
                json: {},
                builtIn: false,
            });
            Loading.hideLoad();
        },
    };
</script>

<style scoped lang="scss">

</style>
